package com.macro.mall.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.macro.mall.utils.DataDecryptUtil;
import com.macro.mall.utils.SignatureUtil;

public class PhoneNumberService {

    private static final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 获取解密后的手机号信息
     * @param rawData 原始数据
     * @param signature 签名
     * @param encryptedData 加密数据
     * @param iv 初始向量
     * @param sessionKey 会话密钥
     * @return 手机号信息对象
     * @throws Exception 校验或解密异常
     */
    public static PhoneNumberInfo getPhoneNumberInfo(String rawData, String signature,
                                                   String encryptedData, String iv,
                                                   String sessionKey) throws Exception {
        // 1. 校验签名
        if (!SignatureUtil.checkSignature(rawData, signature, sessionKey)) {
            throw new SecurityException("签名校验失败");
        }

        // 2. 解密数据
        String decryptedData = DataDecryptUtil.decryptPhoneNumber(encryptedData, sessionKey, iv);

        // 3. 解析JSON
        return objectMapper.readValue(decryptedData, PhoneNumberInfo.class);
    }

    // 手机号信息类
    public static class PhoneNumberInfo {
        private String phoneNumber;
        private String purePhoneNumber;
        private String countryCode;
        private Watermark watermark;

        // getters and setters
        // ...

        @Override
        public String toString() {
            return "PhoneNumberInfo{" +
                    "phoneNumber='" + phoneNumber + '\'' +
                    ", purePhoneNumber='" + purePhoneNumber + '\'' +
                    ", countryCode='" + countryCode + '\'' +
                    ", watermark=" + watermark +
                    '}';
        }
    }

    // 水印信息类
    public static class Watermark {
        private String appId;
        private long timestamp;

        // getters and setters
        // ...

        @Override
        public String toString() {
            return "Watermark{" +
                    "appId='" + appId + '\'' +
                    ", timestamp=" + timestamp +
                    '}';
        }
    }
}
